<script>
import { requestGet, requestPost } from '@/api/system/common'

export default {
  name: 'UserGroupDialog',
  data() {
    return {
      innerVisible: false,
      loading: false,
      groupList: [],
      userList: [],
      pager: 0,
      query: {
        blurry: '',
        page: 1,
        size: 10
      },
      form: {
        users: [],
        groupName: '',
        groupId: ''
      }
    }
  },
  methods: {
    open(data) {
      this.initData()
      this.innerVisible = true
      if (undefined !== data && undefined !== data.id) {
        this.form.groupId = data.id
        this.form.groupName = data.name
        this.initData()
        this.initAllUsers(data.id)
      } else {
        this.form.groupId = ''
        this.form.groupName = ''
        this.form.users = []
      }
    },
    async initData() {
      await requestGet('rest/api/message/v1/inform/user', this.query)
        .then(res => {
          const { data } = res
          this.groupList = data.data
          this.pager = data.pager
        }).catch(() => {
          this.groupList = []
        })
    },
    initAllUsers(groupId) {
      requestGet('rest/api/user/v1/group-notice/users', { gid: groupId, page: 1, size: 1000 })
        .then((res) => {
          const { data } = res
          this.form.users = []
          for (let i = 0; i < data.data.length; i++) {
            console.log(data.data[i].userId)
            const userId = data.data[i].userId
            this.form.users.push(userId)
          }
        })
        .catch(() => {
          this.form.users = []
        })
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          requestPost('rest/api/user/v1/group-notice/save', this.form)
            .then((res) => {
              this.$emit('save', this.form)
              this.innerVisible = false
            }).finally(() => {
              this.loading = false
            })
        }
      })
    },
    close() {
      this.innerVisible = false
      this.form.users = []
      this.form.groupName = ''
      this.form.groupId = ''
    }
  }
}
</script>

<template>
  <el-dialog
    width="60%"
    title="新增用户组"
    :visible.sync="innerVisible"
    append-to-body
  >
    <el-form ref="form" :model="form">
      <el-transfer v-model="form.users" :props="{ key: 'username', label: 'nickName' }" :titles="['未选用户', '已选用户']" :data="groupList" />
      <el-form-item prop="groupName" :rules="{ required: true, message: '请输入用户组名称', trigger: 'blur' }" label="用户组名称">
        <el-input v-model="form.groupName" placeholder="请输入用户组名称" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="innerVisible = false">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save('form')">确认</el-button>
    </div>
  </el-dialog>
</template>

<style scoped>

</style>
